package com.situ.hospital.user.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.situ.hospital.user.dao.IUserDao;
import com.situ.hospital.user.model.UserModel;

import util.JDBCUtil;

public class UserDaoImpl implements IUserDao {
	@Override
	public Integer insert(UserModel user) {
		String sql = "insert into user(username,password) values(?,?)";
		return JDBCUtil.dml(sql, user.getUsername(), user.getPassword());
	}

	@Override
	public Integer deleteByName(UserModel user) throws SQLException {
		String sql = "delete from user where ";
		List<Object> list = new ArrayList<>();
		sql = setSql(sql, list, user, 2);
		return JDBCUtil.dml(sql, list);
	}

	@Override
	public List<UserModel> selectModel(UserModel user) throws SQLException {
		String sql = "select * from user where username=?";
		List<String> maplist=new ArrayList<>();
		List<Object> list=new ArrayList<>();
		list.add(user.getUsername());
		maplist.add("username");
		maplist.add("password");
		return JDBCUtil.dql(sql, list, UserModel.class, maplist);
	}

	@Override
	public Integer updateByName(UserModel user) throws SQLException {
		String sql = "update user set ";
		List<Object> list = new ArrayList<>();
		sql = setSql(sql, list, user, 3);
		return JDBCUtil.dml(sql, list);
	}

	/**
	 * @param sql
	 * @param list
	 * @param department
	 * @param n          1为select 2为delete 3为update
	 * @return
	 */
	private String setSql(String sql, List<Object> list, UserModel user, int m) {
		int n = 0;
		if (user.getUsername() != null && m != 3) {
			if (n == 1) {
				sql += ",";
			} else if (n == 2) {
				sql += " and ";
			}
			sql += "username=?";
			list.add(user.getUsername());
			n = m;
		}
		if (user.getPassword() != null) {
			if (n == 1 || n == 3) {
				sql += ",";
			} else if (n == 2) {
				sql += " and ";
			}
			sql += "password=?";
			list.add(user.getPassword());
			n = m;
		}
		
		if (m == 3) {
			sql += "where username=?";
			list.add(user.getUsername());
		}

//		System.out.println(sql);
		return sql;
	}
}
